package tsing.javase.javaweb.file.controller;

import tsing.javase.javaweb.file.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author Tsing/吴清平
 * @Date 2022/10/11 10:06
 * @Version 1.0
 */

@RestController
@RequestMapping("/file")
public class FileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private FileService fileService;

    /**
     * 文件上传
     */

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file){
        String result = "";
        if(Optional.ofNullable(file).isPresent()){
            fileService.upload(file);
            result = "success";
        }else{
            result = "fail";
        }
        return result;
    }


    /**
     * 文件下载   :返回文件数据
     * @param fileName
     * @param response
     * @return
     */
    @PostMapping("/download")
    public String fileDownload(@RequestParam("fileName") String fileName, HttpServletResponse response){
        if (Objects.isNull(fileName)){
            return "文件下载失败，请选择文件要下载的文件";
        }
        return fileService.download(fileName, response);
    }


    //可以直接在浏览器下载文件
    @GetMapping("/download3")
    public void  download3(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        String fileName = "H:\\file\\upload\\111.txt";
        File file = new File(fileName);
        if (!file.exists()){
            System.out.println("文件不存在");
            return;
        }

        byte[] bytes = new byte[10240];
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
            String header = request.getHeader("User-Agent");
            System.out.println(header);
            if(header.contains("Firefox")){
                System.out.println("使用的是火狐浏览器,使用base64编码");
//                response.addHeader("Content-Disposition", "attachment;fileName=" + new BASE64Encoder().encode(fileName.getBytes()));
            }else {
                System.out.println("使用URLEncode");
                response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));

            }
            outputStream = response.getOutputStream();
            int length;
            while ((length = bufferedInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, length);
            }
            outputStream.flush();
        }catch (Exception e){
            LOGGER.error("文件下载失败", e);
        }finally {
            try {
                if (bufferedInputStream != null){
                    bufferedInputStream.close();
                }

                if (outputStream != null){
                    outputStream.close();
                }

                if (fileInputStream != null){
                    fileInputStream.close();
                }
            }catch (IOException e){
                LOGGER.error(e.getMessage(), e);
            }
        }

    }




    //新鉴权平台使用这种方式

    @PostMapping("/download2")
    public void findFile(HttpServletResponse response,@RequestParam("path")String path) {


        try {
                if (!StringUtils.hasLength(path)) {
                    File f = new File(path);
                    if (!f.exists()) {
                        response.sendError(404, "File not found!");
                        return;
                    }
                    BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
                    byte[] buf = new byte[1024];
                    int len = 0;
                    response.reset(); // 非常重要
                    response.setContentType("octets/stream");
                    response.setContentType("application/x-msdownload");
                    response.setHeader("Content-Disposition", "attachment; filename=" + new String("a.txt".getBytes("UTF-8"), "ISO-8859-1"));

                    OutputStream out = response.getOutputStream();
                    while ((len = br.read(buf)) > 0) {
                        out.write(buf, 0, len);
                    }
                    br.close();
                    out.close();
                }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @GetMapping("/download4")
    public void  download4(HttpServletResponse response){
        String path = "H:\\file\\upload\\111.txt";
        try {
            if (StringUtils.hasLength(path)) {
                File f = new File(path);
                if (!f.exists()) {
                    response.sendError(404, "File not found!");
                    return;
                }
                BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
                byte[] buf = new byte[1024];
                int len = 0;
                response.reset(); // 非常重要
                response.setContentType("octets/stream");
                response.setContentType("application/x-msdownload");
                response.setHeader("Content-Disposition", "attachment; filename=" + new String("a.txt".getBytes("UTF-8"), "ISO-8859-1"));

                OutputStream out = response.getOutputStream();
                while ((len = br.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                br.close();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        String path = "H:\\file\\upload\\111.txt";
        path = path.substring(path.lastIndexOf("\\")+1);
        System.out.println(path);

    }
}
